package org.wejob.core.log;

import java.util.ArrayList;
import java.util.Comparator;

public class Dispatcher {
    //必须是线程安全的
    ArrayList<Writer> writers;
    int cap;
    int threadNum;
    public Dispatcher(){
        this.writers=new ArrayList<>();
        this.cap=4;
        this.threadNum=0;
    }
    public synchronized void dispatch(Topic topic){
        if(threadNum<cap){
            Writer writer=new Writer();
            writer.acceptTask(topic);
            writer.start();
            this.writers.add(writer);
            this.threadNum++;
            return;
        }
        Writer handler=select();
        handler.acceptTask(topic);
    }
    private Writer select(){
        //当前策略按照Topic最小的分配
        return this.writers.stream().min(Comparator.comparingInt(Writer::taskNum)).get();
    }
}
